<template>
  <el-row :gutter="20">
    <el-col :span="16">
      <ContentWrap title="申请信息">
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="100px"
          v-loading="formLoading"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="所属用户ID" prop="userId">
                <el-select
                  v-model="formData.userId"
                  clearable
                  filterable
                  placeholder="请输入所属用户ID"
                  class="!w-240px"
                >
                  <el-option
                    v-for="user in userList"
                    :key="user.id"
                    :label="user.nickname"
                    :value="user.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="续签合同序号" prop="parentId">
                <el-select v-model="formData.parentId" clearable placeholder="请选择续签合同序号">
                  <el-option
                    v-for="item in historyList"
                    :key="item.id"
                    :value="item.id"
                    :label="item.contractNo"
                  />
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="租赁宗地序号" prop="landIds">
                <el-input v-model="formData.landIds" clearable placeholder="请选择宗地" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-button type="primary" @click="openChooseLand">选择宗地</el-button>
            </el-col>

            <el-col :span="12">
              <el-form-item label="合同编号" prop="contractNo">
                <el-input v-model="formData.contractNo" placeholder="请输入合同编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租金额" prop="rentPrice">
                <el-input v-model="formData.rentPrice" placeholder="请输入出租金额" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租期限" prop="rentPeriod">
                <el-input v-model="formData.rentPeriod" placeholder="请输入出租期限" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间" prop="startTime">
                <el-date-picker
                  v-model="formData.startTime"
                  type="date"
                  value-format="x"
                  placeholder="选择开始时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间" prop="endTime">
                <el-date-picker
                  v-model="formData.endTime"
                  type="date"
                  value-format="x"
                  placeholder="选择结束时间"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租位置" prop="rentLocation">
                <el-input v-model="formData.rentLocation" placeholder="请输入出租位置" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租赁土地面积" prop="rentLandarea">
                <el-input v-model="formData.rentLandarea" placeholder="请输入租赁土地面积" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="租赁建筑面积" prop="rentBuildingarea">
                <el-input v-model="formData.rentBuildingarea" placeholder="请输入租赁建筑面积" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="出租方式" prop="rentType">
                <el-select v-model="formData.rentType" placeholder="请选择出租方式">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.RENT_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同签订日期" prop="signingDate">
                <el-date-picker
                  v-model="formData.signingDate"
                  type="date"
                  value-format="x"
                  placeholder="选择合同签订日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="约定交款日期" prop="payDate">
                <el-date-picker
                  v-model="formData.payDate"
                  type="date"
                  value-format="x"
                  placeholder="选择约定交款日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上次交款日期" prop="paidDate">
                <el-date-picker
                  v-model="formData.paidDate"
                  type="date"
                  value-format="x"
                  placeholder="选择上次交款日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="下次交款日期" prop="nextpayDate">
                <el-date-picker
                  v-model="formData.nextpayDate"
                  type="date"
                  value-format="x"
                  placeholder="选择下次交款日期"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="有效状态" prop="effective">
                <el-select v-model="formData.effective" placeholder="请选择有效状态">
                  <el-option
                    v-for="dict in getStrDictOptions(DICT_TYPE.SYS_STATUS)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">
              确 定
            </el-button>
          </el-form-item>
        </el-form>
        <!-- 子表的表单 -->
        <el-tabs v-model="subTabsName">
          <el-tab-pane label="租赁合同档案" name="rentFile">
            <RentFileForm ref="rentFileFormRef" :belong-id="formData.id" />
          </el-tab-pane>
          <el-tab-pane label="宗地信息" name="land">
            <LandForm ref="landFormRef" :land-ids="formData.landIds" />
          </el-tab-pane>
          <el-tab-pane label="年度收益" name="earnings">
            <EarningsForm ref="earningsFormRef" :rent-id="formData.id" />
          </el-tab-pane>
          <el-tab-pane label="承租人信息" name="lessee">
            <LesseeForm ref="lesseeFormRef" :rent-id="formData.id" />
          </el-tab-pane>
          <el-tab-pane label="租金税费管理" name="taxation">
            <TaxationForm ref="taxationFormRef" :rent-id="formData.id" />
          </el-tab-pane>
        </el-tabs>
      </ContentWrap>
    </el-col>

    <!-- 审批相关：流程信息 -->
    <el-col :span="8">
      <ContentWrap title="审批流程" :bodyStyle="{ padding: '0 20px 0' }">
        <ProcessInstanceTimeline
          ref="timelineRef"
          :activity-nodes="activityNodes"
          :show-status-icon="false"
          @select-user-confirm="selectUserConfirm"
        />
      </ContentWrap>
    </el-col>
  </el-row>

  <el-dialog v-model="chooseLandDialogVisible" title="选择宗地" width="70%" append-to-body>
    <ChooseLand ref="chooseLandRef" @land-selected="ChooseLandOK" />
  </el-dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { RentApi, RentVO } from '@/api/zszx/rent'
import RentFileForm from '@/views/zszx/rent/components/RentFileForm.vue'
import LesseeForm from '@/views/zszx/rent/components/LesseeForm.vue'
import TaxationForm from '@/views/zszx/rent/components/TaxationForm.vue'
import EarningsForm from '@/views/zszx/rent/components/EarningsForm.vue'
import LandForm from '@/views/zszx/rent/components/LandForm.vue'

import * as UserApi from '@/api/system/user'
const userList = ref<UserApi.UserVO[]>([]) // 用户列表

import { useTagsViewStore } from '@/store/modules/tagsView'
// 审批相关：import
import * as DefinitionApi from '@/api/bpm/definition'
import ProcessInstanceTimeline from '@/views/bpm/processInstance/detail/ProcessInstanceTimeline.vue'
import * as ProcessInstanceApi from '@/api/bpm/processInstance'
import { CandidateStrategy, NodeId } from '@/components/SimpleProcessDesignerV2/src/consts'
import { ApprovalNodeInfo } from '@/api/bpm/processInstance'

import ChooseLand from '@/views/zszx/land/ChooseLand.vue'

const chooseLandDialogVisible = ref(false)

/** 选择土地 */
const chooseLandRef = ref()
const openChooseLand = () => {
  chooseLandDialogVisible.value = true
}
function ChooseLandOK(data) {
  console.log(data, data.id)
  if (
    formData.value.landIds != '' &&
    formData.value.landIds != undefined &&
    formData.value.landIds != null
  ) {
    const ids = new Set(formData.value.landIds.split(',')) // 拆分为数组并去重
    ids.add(data.id.toString()) // 添加新 ID（自动去重）
    formData.value.landIds = Array.from(ids).join(',') // 重新拼接为字符串
  } else {
    formData.value.landIds = data.id.toString() //统一为字符串
  }
  chooseLandDialogVisible.value = false
}

/** 租赁合同管理 表单 */
defineOptions({ name: 'CreateRentApprove' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { delView } = useTagsViewStore() // 视图操作
const { push, currentRoute } = useRouter() // 路由

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('表单的类型：create') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  processInstanceId: undefined,
  parentId: undefined,
  proposerId: undefined,
  status: undefined,
  effective: '0',
  landIds: '',
  userId: undefined,
  contractNo: undefined,
  rentPrice: undefined,
  rentPeriod: undefined,
  startTime: undefined,
  endTime: undefined,
  rentLocation: undefined,
  rentLandarea: undefined,
  rentBuildingarea: undefined,
  rentType: undefined,
  signingDate: undefined,
  payDate: undefined,
  paidDate: undefined,
  nextpayDate: undefined,
  remark: undefined
})
const formRules = reactive({
  landIds: [{ required: true, message: '租赁宗地序号不能为空', trigger: 'blur' }],
  contractNo: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
  rentPrice: [{ required: true, message: '出租金额不能为空', trigger: 'blur' }],
  startTime: [{ required: true, message: '开始时间不能为空', trigger: 'blur' }],
  endTime: [{ required: true, message: '结束时间不能为空', trigger: 'blur' }],
  payDate: [{ required: true, message: '约定交款日期不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 子表的表单 */
const subTabsName = ref('rentFile')
const rentFileFormRef = ref()
const lesseeFormRef = ref()
const taxationFormRef = ref()
const earningsFormRef = ref()
const landFormRef = ref()

// 审批相关：变量
const processDefineKey = 'yw_rentapprove' // 流程定义 Key
const startUserSelectTasks = ref([]) // 发起人需要选择审批人的用户任务列表
const startUserSelectAssignees = ref({}) // 发起人选择审批人的数据
const tempStartUserSelectAssignees = ref({}) // 历史发起人选择审批人的数据，用于每次表单变更时，临时保存
const activityNodes = ref<ProcessInstanceApi.ApprovalNodeInfo[]>([]) // 审批节点信息
const processDefinitionId = ref('')

const historyList = ref([])

/** 初始化 */
onMounted(async () => {
  // TODO @小北：这里可以简化，统一通过 getApprovalDetail 处理么？
  const processDefinitionDetail = await DefinitionApi.getProcessDefinition(
    undefined,
    processDefineKey
  )

  if (!processDefinitionDetail) {
    message.error('OA 请假的流程模型未配置，请检查！')
    return
  }
  processDefinitionId.value = processDefinitionDetail.id
  startUserSelectTasks.value = processDefinitionDetail.startUserSelectTasks

  // 审批相关：加载最新的审批详情，主要用于节点预测
  await getApprovalDetail()

  // 获得用户列表
  userList.value = await UserApi.getSimpleUserList()

  historyList.value = await RentApi.historyList()
})

/** 审批相关：预测流程节点会因为输入的参数值而产生新的预测结果值，所以需重新预测一次, formData.value可改成实际业务中的特定字段 */
watch(
  formData.value,
  (newValue, oldValue) => {
    if (!oldValue) {
      return
    }
    if (newValue && Object.keys(newValue).length > 0) {
      // 记录之前的节点审批人
      tempStartUserSelectAssignees.value = startUserSelectAssignees.value
      startUserSelectAssignees.value = {}
      // 加载最新的审批详情,主要用于节点预测
      getApprovalDetail()
    }
  },
  {
    immediate: true
  }
)

/** 审批相关：选择发起人 */
const selectUserConfirm = (id: string, userList: any[]) => {
  startUserSelectAssignees.value[id] = userList?.map((item: any) => item.id)
}

/** 审批相关：获取审批详情 */
const getApprovalDetail = async () => {
  try {
    const data = await ProcessInstanceApi.getApprovalDetail({
      processDefinitionId: processDefinitionId.value,
      // TODO 小北：可以支持 processDefinitionKey 查询
      activityId: NodeId.START_USER_NODE_ID,
      processVariablesStr: {} // 解决 GET 无法传递对象的问题，后端 String 再转 JSON
    })

    if (!data) {
      message.error('查询不到审批详情信息！')
      return
    }
    // 获取审批节点，显示 Timeline 的数据
    activityNodes.value = data.activityNodes

    // 获取发起人自选的任务
    startUserSelectTasks.value = data.activityNodes?.filter(
      (node: ApprovalNodeInfo) => CandidateStrategy.START_USER_SELECT === node.candidateStrategy
    )
    // 恢复之前的选择审批人
    if (startUserSelectTasks.value?.length > 0) {
      for (const node of startUserSelectTasks.value) {
        if (
          tempStartUserSelectAssignees.value[node.id] &&
          tempStartUserSelectAssignees.value[node.id].length > 0
        ) {
          startUserSelectAssignees.value[node.id] = tempStartUserSelectAssignees.value[node.id]
        } else {
          startUserSelectAssignees.value[node.id] = []
        }
      }
    }
  } finally {
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await RentApi.getRent(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 1.1 校验表单
  if (!formRef) return
  // 校验表单
  const valid = await formRef.value.validate()
  if (!valid) return
  // 校验子表单
  try {
    await rentFileFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rentFile'
    return
  }
  try {
    await landFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'land'
    return
  }
  try {
    await lesseeFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'lessee'
    return
  }
  try {
    await taxationFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'taxation'
    return
  }
  try {
    await earningsFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'earnings'
    return
  }
  // 1.2 审批相关：校验指定审批人
  if (startUserSelectTasks.value?.length > 0) {
    for (const userTask of startUserSelectTasks.value) {
      if (
        Array.isArray(startUserSelectAssignees.value[userTask.id]) &&
        startUserSelectAssignees.value[userTask.id].length === 0
      ) {
        return message.warning(`请选择${userTask.name}的审批人`)
      }
    }
  }

  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as RentVO
    // 拼接子表的数据
    data.lands = landFormRef.value.getData()
    data.lessees = lesseeFormRef.value.getData()
    data.taxations = taxationFormRef.value.getData()
    data.earningss = earningsFormRef.value.getData()
    await RentApi.createRentApprove(data)
    message.success(t('common.createBpmSuccess'))
    // 关闭当前 Tab
    delView(unref(currentRoute))
    await push({ name: 'RentApprove' })
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    parentId: undefined,
    processInstanceId: undefined,
    status: undefined,
    effective: '0',
    proposerId: undefined,
    landIds: '',
    userId: undefined,
    contractNo: undefined,
    rentPrice: undefined,
    rentPeriod: undefined,
    startTime: undefined,
    endTime: undefined,
    rentLocation: undefined,
    rentLandarea: undefined,
    rentBuildingarea: undefined,
    rentType: undefined,
    signingDate: undefined,
    payDate: undefined,
    paidDate: undefined,
    nextpayDate: undefined,
    remark: undefined
  }
  formRef.value?.resetFields()
}
</script>
